import sys
sys.path.append("..")

import numpy as np
from matplotlib import pyplot as plt
from som import SOMFactory
import pandas as pd
import seaborn as sns
import datetime


def seasonal(x):
	current_date = datetime.datetime.strptime("%d"%x,"%Y-%m-%d")
	if current_date.month >=3 and current_date.month < 6:
		return 0
	elif current_date.month >= 6 and current_date.month < 9:
		return 1
	elif current_date.month >= 9 and current_date.month < 12:
		return 2
	else:
		return 3

def month(x): 
	return (datetime.datetime.strptime("%d"%x,"%Y%j")).month

def z_score(x):
	if abs(x) > 3.29:
		return 5
	elif abs(x) > 2.575:
		return 4
	elif abs(x) > 1.96:
		return 3
	elif abs(x) > 1.645:
		return 2
	else:
		return 1


def direction(x):
	if x == -1:
		return 9
	elif x < 22.5 or x > 337.5:
		return 1
	elif x >= 22.5 and x < 67.5:
		return 2
	elif x >= 67.5 and x < 112.5:
		return 3
	elif x >= 112.5 and x < 157.5:
		return 4
	elif x >= 157.5 and x < 202.5:
		return 5
	elif x >= 202.5 and x < 247.5:
		return 6
	elif x >= 247.5 and x < 292.5:
		return 7
	elif x >= 292.5 and x < 337.5:
		return 8
	else:
		return 9
data = pd.read_table("/mnt/fire/fire_event4.txt")

data_frm = data[(data["fmc_m"] > 0)]
data_frm = data_frm[data_frm["lai_0"] < 250]
data_frm = data_frm.dropna(axis =0,how="any")

print(data_frm.info())
# data_frm = data_frm[data_frm.rfe_0 < 10]
# print(data_frm["rfe_0"].max())

label=["Spring","Summer","Autumn","Winter"]

lab_month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
names = ["lat",'lon','aspect','slope','fmc_0','ndvi_0','lai_0','t2m_0','m2m_0','wns_0','rh_0','rfe_0']

dir_label = ["N","NE","E","SE","S","SW","W","NW","F"] # 2
slope_label = ["I","II","III","IV","V","VI"] # 1
conf_label = ["N","90%","95%","99%","99.9%"] # 4
anomaly_label = ["ED","D","LD","LU","U","EU"]  #L: Light  D: Down U: Up 4
fmc_label=["fEL","fL","fM","fH","fEH"] #1
trend_label = ["ED","D","U","EU"]#4
alt_label = ["BM","LM","MM","HM","EM"] # B: Brent/Hill M:Mountain E:extrem #1
dlr_label = ["dES","dS","dM","dL","dEL"]#
ld_label = ["lEN","lN","lF","lEF"]
tp_label = ["tS","tM","tL","tRS"]
mean_lable=["L","M","H","EH"]


trans = pd.DataFrame()
# for row in data_frm.iterrows():
# 	print(row)
trans["alt"] = pd.cut(data_frm["alt"],[0,1000,1500,2000,3500,9000],right=False,labels=alt_label)
trans["slope"] = pd.cut(data_frm["slope"],[0,6,16,26,36,46,90],right=False,labels=slope_label)
trans["aspect"] = pd.cut(data_frm["aspect"].map(direction),range(1,11),right=False,labels=["a%s"%x for x in dir_label])
trans["ld"] = pd.cut(data_frm["ld"],[0,5000,10000,20000,10*111*1000],right=False,labels=ld_label)
trans["wnd"] = pd.cut(data_frm["wnd"].map(direction),range(1,11),right=False,labels=["w%s"%x for x in dir_label])
trans["dlr"] = pd.cut(data_frm["dlr"],[0,5,10,20,30,365],right=False,labels=dlr_label)
trans["fmc_t"] = pd.cut(data_frm["fmc_t"],[-100,-1,0,1,100],right=False,labels=["f_t%s"%x for x in trend_label])
trans["rh_t"] = pd.cut(data_frm["rh_t"],[-100,-0.5,0,0.5,100],right=False,labels=["r_t%s"%x for x in trend_label])
trans["t2m_t"] = pd.cut(data_frm["t2m_t"],[-100,-0.2,0,0.2,100],right=False,labels=["t_t%s"%x for x in trend_label])
trans["wns_t"] = pd.cut(data_frm["wns_t"],[-100,-0.05,0,0.05,100],right=False,labels=["w_t%s"%x for x in trend_label])
trans["fmc_m"] = pd.cut(data_frm["fmc_m"],[0,50,80,100,150,300],right=False,labels=fmc_label)
trans["tp_m"] = pd.cut(data_frm["tp_m"],[0,50,100,150,365*150],right=False,labels=tp_label)
trans["rh_m"] = pd.cut(data_frm["rh_m"],[0,40,60,80,100],right=False,labels=["r%s"%x for x in mean_lable])
trans["t2m_m"] = pd.cut(data_frm["t2m_m"]-273.15,[-30,10,15,25,60],right=False,labels=["t%s"%x for x in mean_lable])

for var in ["fmc","t2m","rh","wns"]:
	trans["%s_z"%var] = pd.cut(data_frm["%s_z"%var].map(z_score),range(1,7),right=False,labels=["%s_z%s"%(var[0],x) for x in conf_label])
	trans["%s_a"%var] = pd.cut(data_frm["%s_a"%var],[-100,-2,-0.5,0,0.5,2,100],right=False,labels=["%s_a%s"%(var[0],x) for x in anomaly_label])

trans["fire"]=data_frm["fire"]

trans.to_csv("/mnt/fire/fire_event_dis_new.csv")


# fire_som_data = data_frm[names]

# som_fire = SOMFactory().build(np.array(fire_som_data), mapsize = (20,20),initialization = 'random',component_names = names)
# som_fire.train(train_rough_len=300, train_finetune_len=200)

# topographic_error = som_fire.calculate_topographic_error()
# quantization_error = np.mean(som_fire._bmu[1])
# print ("Topographic error = %s; Quantization error = %s" % (topographic_error, quantization_error))

# from visualization.mapview import View2DPacked
# # v = View2DPacked(50,50,'test',text_size = 12)
# # v.show(som_fire,col_sz = 6)

# cl = som_fire.cluster(n_clusters = 6)

# v = View2DPacked(150, 150, '',text_size=8) 
# plt = v.show(som_fire, what='cluster') 

# # v.show(som_fire,what = 'cluster',col_sz = 6)
# # v.show(som_fire,what='all',col_sz = 6)

# from visualization.mapview import View2D
# view2D  = View2D(150,150,"",text_size=12)
# plt = view2D.show(som_fire, col_sz=4, which_dim="all", desnormalize=True,cmap = 'jet')


# # #### Hits map

# # In[12]:


# from visualization.bmuhits import BmuHitsView

# vhts  = BmuHitsView(150,150,"",text_size=12)
# plt = vhts.show(som_fire, anotate=True, onlyzeros=False, labelsize=12, cmap="jet", logaritmic=False)


# from visualization.umatrix import UMatrixView

# umatrix = UMatrixView(150,150,'umatrix',show_axis = True, text_size = 12, show_text = 'True')

# UMAT = umatrix.build_u_matrix(som_fire,distance = 1, row_normalized = False)

# UMAT = umatrix.show(som_fire,distance2 =1, row_normalized=False,show_data = True, contooor = True, blob=False)



# hits  = HitMapView(20,20,"Clustering",text_size=12)
# data_frm["season"] = pd.cut(data_frm.doy,[0,60,152,244,335,366],right = False,labels = label)
# count = pd.value_counts(data_frm["season"])
# print(count)

# col_name = data_frm.columns.tolist()

# col_name.insert(2,"season")

# data_frm.reindex(columns = col_name)

# print(data_frm)

# data_frm["season"] = pd.cut(data_frm['date'].map(seasonal),[0,1,2,3,4],right = False,labels = label)
# data_frm["month"] = pd.cut(data_frm['date'].map(month),range(1,14),right = False,labels = lab_month)
# # count = pd.value_counts(data_frm["season"],sort = False)
# # count_mon = pd.value_counts(data_frm["month"],sort = False)
# # count_mon.plot.bar()
# print(plt.rcParams.keys())
plt.rcParams['font.serif']=['Times New Roman'] 
# count.plot.bar()
plt.xticks(fontsize=12) #默认字体大小为10 
plt.yticks(fontsize=12) 

# sns.set_style("white")
# sns.set_context("notebook")

# # ax = sns.barplot(x="season", y="values", data=count)
# ax = sns.countplot(x = "season", data = data_frm,palette="Set3")
# ax.set_xlabel('Season', fontsize = 12)
# ax.set_ylabel('Count', fontsize = 12)
# ax.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/Season.svg',format = "svg")

# plt.figure()
# ax_month = sns.countplot(x = "month", data = data_frm)
# ax_month.set_xlabel('Month', fontsize = 12)
# ax_month.set_ylabel('Count', fontsize = 12)
# ax_month.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/Monthly.svg',format = "svg")

# plt.figure()
# ax_fmc = sns.distplot(data_frm['m2m_0'],color = 'r', kde = False,norm_hist = False)
# ax_fmc.set_xlabel('Daily Maximum Air Temperature', fontsize = 12)
# ax_fmc.set_ylabel('Frequent', fontsize = 12)
# ax_fmc.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/m2m.svg',format = "svg")

# plt.figure()
# ax_fmc = sns.distplot(data_frm['t2m_0'],color = 'r', kde = False,norm_hist = False)
# ax_fmc.set_xlabel('Air Temperature', fontsize = 12)
# ax_fmc.set_ylabel('Frequent', fontsize = 12)
# ax_fmc.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/t2m.svg',format = "svg")

# plt.figure()
# ax_fmc = sns.distplot(data_frm['fmc_0'],color = 'r', kde = False,norm_hist = False)
# ax_fmc.set_xlabel('FMC', fontsize = 12)
# ax_fmc.set_ylabel('Frequent', fontsize = 12)
# ax_fmc.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/fmc.svg',format = "svg")

# plt.figure()
# ax_fmc = sns.distplot(data_frm['rh_0'],color = 'r', kde = False,norm_hist = False)
# ax_fmc.set_xlabel('Relative Humidity (%)', fontsize = 12)
# ax_fmc.set_ylabel('Frequent', fontsize = 12)
# ax_fmc.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/rh.svg',format = "svg")
# plt.show()
# print(data_frm['rfe_0'].max())

ax_fmc = sns.distplot(data_frm["t2m_m"] - 273.15,color = 'r', kde = False, norm_hist = False)
ax_fmc.set_xlabel('Days after last rainfall (mm)', fontsize = 12)
ax_fmc.set_ylabel('Frequent', fontsize = 12)

# data_frm["fmc_zc"] = pd.cut(data_frm['wns_z'].map(z_score),range(1,7),right = False)
# g = sns.lmplot(x="wns_z",y="wns_t",hue="fmc_zc",data=data_frm,fit_reg=False)



# ax_fmc.tick_params(labelsize=12)
# plt.savefig('/home/hugo/Documents/Figure/precip.svg',format = "svg")
plt.show()


